package com.ruoyi.wx.utils;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.user.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class GetUserUtils {
    public static User getLoginUser(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token) && token.startsWith("Bearer ")) {
            RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
            String redisKey = WxConstants.LOGIN_TOKEN_KEY + token;
            User loginUser = redisCache.getCacheObject(redisKey);
            if (loginUser != null) {
                return loginUser;
            }
        }
        // 未登录，抛出异常
        throw new UnauthorizedException(IpUtils.getIpAddr() + "未登录或登录已过期");
    }


    public static AjaxResult logout(HttpServletRequest request) {
        // 从请求头获取 token
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token) && token.startsWith("Bearer ")) {
            String redisKey = WxConstants.LOGIN_TOKEN_KEY + token;

            // 删除 Redis 缓存
            RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
            boolean removed = redisCache.deleteObject(redisKey);

            if (removed) {
                log.info("用户退出成功，token 已清除: {}", token);
            } else {
                log.warn("退出登录时未找到 token: {}", token);
            }
        } else {
            log.warn("退出登录失败：未传递有效的 token");
            return AjaxResult.error("退出登录失败，未传递有效 token");
        }
        return AjaxResult.success("退出成功");
    }
}
